package com.xbn.netty.coder2;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;

/**
 * @author XBN
 * @date 2020/10/19 13:57
 * @email 78742541@qq.com
 */
/*
* 客户端
* */
public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        //客户端只需要一个事件循环组
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //创建一个客户端启动对象
            //客户端使用的不是ServerBootStrap  而是BootStrap
            Bootstrap bootstrap = new Bootstrap();
            //设置相关参数
            bootstrap.group(workerGroup)  //设置线程组
                    .channel(NioSocketChannel.class)  //设置客户端通道的实现了
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //加入protobuf编码器,注意这个编码器一定要加在自定义处理器之前
                            //也就是编码器一定要在我们发送数据之前
                            socketChannel.pipeline().addLast("encoder",new ProtobufEncoder());
                            //加入自定义处理器
                            socketChannel.pipeline().addLast(new NettyClientHandler());

                        }
                    });
            System.out.println("客户端ok");
            //启动客户端去连接服务器端,涉及到netty的异步模型
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6668).sync();
            //给关闭通道增加一个监听
            channelFuture.channel().closeFuture().sync();
        }finally {
            //优雅的关闭shutdownGracefully
            workerGroup.shutdownGracefully();
        }
    }



}
